package com.tedu.dao.impl;

import com.tedu.dao.EmpDao;
import com.tedu.entity.Emp;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EmpDaoImpl implements EmpDao {


    @Override
    public List<Emp> findAllEmp() {
        ArrayList<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/ankang",
                    "root",
                    "root"
            );
            String sql = "select * from emp";
            PreparedStatement pstm = conn.prepareStatement(sql);
            ResultSet rs = pstm.executeQuery();
            while (rs.next()) {
                emps.add(
                        new Emp(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getDouble(3),
                        rs.getDate(4),
                        rs.getDate(5),
                        rs.getDate(6),
                        rs.getInt(7)
                ));
            }
            rs.close();
            pstm.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return emps;
    }

    @Override
    public Emp findEmpById(int id) {
        return null;
    }

    @Override
    public void deleteEmpById(int id) {

    }

    @Override
    public void updateEmpById(Emp emp) {

    }

    @Override
    public void insertEmp(Emp emp) {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/ankang?characterEncoding=UTF-8",
                    "root",
                    "root"
            );
            String sql = "insert emp(name,salary,birthday,hiretime,dimission,deptid) value(?,?,?,?,?,?)";
            PreparedStatement pstm = conn.prepareStatement(sql);
            pstm.setString(1, emp.getName());
            pstm.setDouble(2, emp.getSalary());
            Date birthday = emp.getBirthday();
            long time = birthday.getTime();
            java.sql.Date bir = new java.sql.Date(time);
            pstm.setDate(3, bir);
            Date hiredate = emp.getHiredate();
            java.sql.Date hiretime = new java.sql.Date(hiredate.getTime());
            pstm.setDate(4, hiretime);
            pstm.setDate(5, null);
            pstm.setInt(6, emp.getDeptid());
            int num = pstm.executeUpdate();
            System.out.println("影响了"+num+"行");
            pstm.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
